//
//  SMHomeViewModel.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/8.
//

import Foundation

class SMHomeViewModel: ObservableObject {
    @Published var homeListData: HomeListData?
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    // 处理后的数据
    @Published var largeCardModel: Septenier?
    @Published var smallCardModel: Septenier?
    @Published var productListModel: Septenier?
    @Published var repaymentModel: Septenier?
    @Published var topReceiveer: Receiveer?
    
    func loadHomeData() {
        isLoading = true
        errorMessage = nil
        
        LYStocksManager.fetchMotherling { [weak self] homeListData, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = msg
                    print("请求失败: \(error)")
                    return
                }
                
                guard let homeListData = homeListData else {
                    self.errorMessage = "数据为空"
                    return
                }
                
                self.homeListData = homeListData
                self.processHomeData(homeListData)
            }
        }
    }
    
    private func processHomeData(_ homeListData: HomeListData) {
        guard let septenier = homeListData.septenier else { return }
        
        // 分离数据处理逻辑
        processCardModels(septenier)
        processProductList(septenier)
        processRepaymentData(septenier)
    }
    
    private func processCardModels(_ septenier: [Septenier]) {
        // 大卡位数据
        largeCardModel = septenier.first { $0.storyitious == "cordit" }
        
        // 小卡位数据
        smallCardModel = septenier.first { $0.storyitious == "ruberamongcy" }
        
        // 设置顶部接收器
        if let corditModel = largeCardModel ?? smallCardModel {
            topReceiveer = corditModel.receiveer.first
        }
    }
    
    private func processProductList(_ septenier: [Septenier]) {
        productListModel = septenier.first { $0.storyitious == "scabrfier" }
    }
    
    private func processRepaymentData(_ septenier: [Septenier]) {
        repaymentModel = septenier.first { $0.storyitious == "torquesque" }
    }
    
    // 获取图片 URL
    func getImageURL() -> String? {
        guard let baseURL = topReceiveer?.juxtaette else { return nil }
        let queryString = NetworkManager.shared.commonParameters.urlQueryString
        return "\(baseURL)?\(queryString)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    }
    
    // 获取导航标题
    var navigationTitle: String {
        return topReceiveer?.argue ?? ""
    }
}
